<template>
  <div class="edit-category">
    <div>
      <i class="el-icon-edit-outline" @click="dialogVisible=true"></i>
    </div>
    <el-dialog :visible.sync="dialogVisible" title="编辑分类">
      <el-form label-position="left" label-width="100px" ref="form" :model="form">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="分类图片" prop="fileList">
          <el-upload class="upload-demo" action="http://122.112.175.16:1234/tmall_springboot/categories/update" :limit="1"
            :before-upload="handleBeforeUpload" ref="upload" :file-list="form.fileList" v-model="form.fileList" :data="{name:form.name,id:form.id}"
            :auto-upload="false" :on-success="handleSuccess" name="image">
            <el-button size="small" type="primary" plain>点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="submit">
          <el-button type="success" @click="commit()">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import {
    editCategory
  } from '@/api/admin/category.js'
  export default {
    data() {
      return {
        dialogVisible: false,
        fileList: [],
      }
    },
    props: {
      form: {
        type: Object
      },
    },
    methods: {
      handleBeforeUpload(file) {
        if(!this.form.name){
        	this.$message.error('名称不能为空')
        	return false
        }
      },
      commit() {
        this.$refs.upload.submit()
      },
      uploadFile(e) {
        let formData = new FormData()
        formData.append('name', this.form.name)
        formData.append('image', e.file)
        formData.append('id', this.form.id)
        editCategory(formData).then(response => {
          this.$message({
            type: 'success',
            message: '编辑成功'
          })
          this.dialogVisible = false
          this.$emit('flash')
          this.$refs.form.resetFields()
          this.form.fileList = []
        })
      },
	  handleSuccess() {
	    this.$message({
	      type: 'success',
	      message: '编辑成功'
	    })
	    this.dialogVisible = false
	    this.$emit('flash')
	    this.$refs.form.resetFields()
	    this.form.fileList = []
	  }
    },
  }
</script>

<style scoped>
  .edit-category {
    text-align: left;
  }

  .edit-category>div:first-child {
    text-align: center;
  }

  i:hover {
    color: #409EFF;
  }

  i {
    font-size: 20px;
  }
</style>
